package post

import (
	"context"
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/text/gstr"
	"github.com/gogf/gf/v2/util/gconv"
	"ruoyi-vue-pro-go/api/common"
	v1 "ruoyi-vue-pro-go/api/post/v1"
	"ruoyi-vue-pro-go/internal/consts"
	"ruoyi-vue-pro-go/internal/dao"
	"ruoyi-vue-pro-go/internal/model/do"
	"ruoyi-vue-pro-go/internal/model/entity"
	"ruoyi-vue-pro-go/internal/service"
	"ruoyi-vue-pro-go/utility/excel"
)

type (
	sPost struct{}
)

func init() {
	service.RegisterPost(New())
}

func New() service.IPost {
	return &sPost{}
}

func (s *sPost) GetOne(ctx context.Context, req *v1.GetOneReq) (res *v1.GetOneRes, err error) {
	res = &v1.GetOneRes{}
	err = dao.SystemPost.Ctx(ctx).Where(do.SystemPost{
		Id: req.Id,
	}).Scan(&res.SystemPost)
	return
}

func (s *sPost) GetList(ctx context.Context, req *v1.GetListReq) (res *v1.GetListRes, err error) {
	res = &v1.GetListRes{}
	err = dao.SystemPost.Ctx(ctx).Scan(&res.List)
	return
}

func (s *sPost) GetPage(ctx context.Context, req *v1.GetPageReq) (res *v1.GetPageRes, err error) {
	res = &v1.GetPageRes{
		List:          make([]*entity.SystemPost, 0),
		CommonPageRes: &common.CommonPageRes{},
	}
	model := dao.SystemPost.Ctx(ctx)
	if req.Name != "" {
		model = model.WhereLike("name", "%"+req.Name+"%")
	}
	if req.Code != "" {
		model = model.WhereLike("code", "%"+req.Code+"%")
	}
	if req.Status != -1 {
		model = model.Where("status = ?", req.Status)
	}
	if req.PageSize != 0 {
		res.PageNo = req.PageNo
		res.PageSize = req.PageSize
		model = model.Page(req.PageNo, req.PageSize)
	}
	err = model.ScanAndCount(&res.List, &res.Total, false)
	return
}

func (s *sPost) Update(ctx context.Context, req *v1.UpdateReq) (res *v1.UpdateRes, err error) {
	res = &v1.UpdateRes{}
	// 这里需要获取当前用户名和租户id
	r := ghttp.RequestFromCtx(ctx)
	username := r.GetCtxVar("username").String()
	tenantId := gconv.Int64(r.Header.Get("Tenant-Id"))
	req.TenantId = tenantId
	req.Creator = username
	req.Updater = username
	_, err = dao.SystemPost.Ctx(ctx).Data(req).Where(do.SystemPost{
		Id: req.Id,
	}).Update()
	if err != nil {
		return nil, gerror.NewCode(gcode.CodeDbOperationError, "user update failed")
	}
	return
}

func (s *sPost) Create(ctx context.Context, req *v1.CreateReq) (res *v1.CreateRes, err error) {
	res = &v1.CreateRes{}
	// 这里需要获取当前用户名和租户id
	r := ghttp.RequestFromCtx(ctx)
	username := r.GetCtxVar("username").String()
	tenantId := gconv.Int64(r.Header.Get("Tenant-Id"))
	req.TenantId = tenantId
	req.Creator = username
	req.Updater = username
	var cls = dao.SystemPost.Columns()
	count, err := dao.SystemPost.Ctx(ctx).
		Where(cls.Name, req.Name).Count()
	if err != nil {
		return res, err
	}
	if count > 0 {
		return res, gerror.NewCode(gcode.CodeDbOperationError, "岗位已存在")
	}
	_, err = dao.SystemPost.Ctx(ctx).Data(req).Insert()
	if err != nil {
		return res, gerror.NewCode(gcode.CodeDbOperationError, "post create failed")
	}
	return
}

func (s *sPost) Delete(ctx context.Context, req *v1.DeleteReq) (res *v1.DeleteRes, err error) {
	res = &v1.DeleteRes{}
	var cls = dao.SystemPost.Columns()
	_, err = dao.SystemPost.Ctx(ctx).Where(cls.Id, req.Id).Delete()
	if err != nil {
		return nil, gerror.NewCode(gcode.CodeDbOperationError, "post delete failed")
	}
	return
}

func (s *sPost) DeleteList(ctx context.Context, req *v1.DeleteListReq) (res *v1.DeleteListRes, err error) {
	res = &v1.DeleteListRes{}
	var cls = dao.SystemPost.Columns()
	// 参数转换
	ids := gconv.Ints(gstr.Split(req.Ids, ","))
	if len(ids) == 0 {
		return nil, gerror.New("无效的ID参数")
	}
	_, err = dao.SystemPost.Ctx(ctx).WhereIn(cls.Id, ids).Delete()
	if err != nil {
		return nil, gerror.NewCode(gcode.CodeDbOperationError, "post delete list failed")
	}

	return
}

func (s *sPost) ExportExcel(ctx context.Context, req *v1.ExportExcelReq) (res *v1.ExportExcelRes, err error) {
	res = &v1.ExportExcelRes{}
	// 1. 获取岗位数据
	postList, err := service.Post().GetList(ctx, &v1.GetListReq{})
	if err != nil {
		return nil, gerror.Wrap(err, "获取岗位数据失败")
		// 2. 创建导出器
		exporter := excel.NewGenericExporter(
			"岗位列表.xlsx",
			postList.List,
			excel.WithFields(consts.PostExportFieldsOrder...),
			excel.WithHeaderMap(consts.PostExportFields),
		)

		// 3. 执行导出
		r := ghttp.RequestFromCtx(ctx)
		if err := exporter.Export(ctx, r.Response); err != nil {
			return nil, gerror.Wrap(err, "导出岗位列表失败")
		}

		// 4. 终止后续处理
		r.ExitAll()
		return nil, nil
	}
	return
}
